package com.jszc.lottery.common.datatest;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Created by Administrator on 2016/4/28.
 */
public class JsonUtil {

    private static ObjectMapper mapper = new ObjectMapper();

    private static boolean isInited = false;
    /**
     * 初始化JsonUtil工具包
     */
    public static void init(){
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        mapper.setDateFormat(fmt);
        isInited = true;
    }

    /**
     * 把对象转化成json字符串
     */
    public static <TObject extends Object> String objToJson(TObject obj) {
        try {
            if(!isInited){
                init();
            }

            if (obj == null) return StrUtil.emptyString;
            return mapper.writeValueAsString(obj);
        } catch (Exception ex) {
            throw new CommonException("Object转化Json字符串异常", ex);
        }
    }

    /**
     * json字符串转化成对象
     */
    public static <TObject extends Object> TObject jsonToObj(Class<TObject> cls, String jsonStr) {
        try {
            if(!isInited){
                init();
            }

            if (StrUtil.isTEpt(jsonStr)) return null;
            return mapper.readValue(jsonStr, cls);
        } catch (Exception ex) {
            throw new CommonException("Json字符串转化Object异常：" + jsonStr, ex);
        }
    }

    /**
     * json字符串转化成对象数祖
     */
    public static <TObject extends Object> List<TObject> jsonToObjList(Class<TObject> cls, String jsonStr) {
        try {
            if(!isInited){
                init();
            }

            if (StrUtil.isTEpt(jsonStr)) return null;
            JavaType javaType = mapper.getTypeFactory().constructParametricType(
                    List.class, cls);
            List<TObject> objList = mapper.readValue(jsonStr, javaType);
            return objList;
        } catch (Exception ex) {
            throw new CommonException("Json字符串转化List<TObject>异常", ex);
        }
    }
}




